package net.spacebeeshooter.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;

import net.spacebeeshooter.main.ErrorGenerator;

public class SaveListener implements ActionListener {

	private TableSaver saver;
	private TabPanel tabPanel;
	
	public SaveListener(TableSaver saver, TabPanel tabPanel) {
		this.saver = saver;
		this.tabPanel = tabPanel;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser();
		if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			File outputFile = chooser.getSelectedFile();
			try {
				BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
				saver.saveTable(writer, tabPanel.getTables());
				writer.close();
			} catch (IOException ex) {
				new ErrorGenerator().generateErrorMessage("Saving failed.");
			}
			
		}
		
	}

}
